const api = require('../../utils/api')
const { networkHelper } = require('../../utils/network-helper')
const { safeGet, completeOrder } = require('../../utils/data-validator')
const { httpErrorHandler } = require('../../utils/http-error-handler')

Page({
  data: {
    selectedStatus: 'all',
    orders: [],
    currentPage: 0,
    hasMore: true,
    loading: false,
    
    // 取消订单
    showCancelModal: false,
    selectedOrder: null,
    selectedReason: '',
    cancelReasons: [
      '不想要了',
      '商品信息填错了',
      '地址填写错误',
      '优惠券使用错误',
      '其他原因'
    ]
  },

  onLoad() {
    this.loadOrders()
  },

  onShow() {
    // 刷新订单列表
    this.refreshOrders()
  },

  onPullDownRefresh() {
    this.refreshOrders()
  },

  // 加载订单列表
  async loadOrders() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    try {
      // 获取app实例
      const app = getApp()
      
      // 获取用户ID，提供多种降级方案
      const userId = app && app.globalData && app.globalData.userInfo ? app.globalData.userInfo.id : 
                    wx.getStorageSync('userId') || 
                    1 // 默认用户ID
      
      console.log('获取订单列表 - 用户ID:', userId, '状态筛选:', this.data.selectedStatus)
      
      // 使用网络助手进行API调用，自动处理网络异常
      const orders = await networkHelper.apiRequest(
        () => api.getUserOrders(userId, 
          this.data.selectedStatus === 'all' ? null : this.data.selectedStatus),
        {
          fallbackData: this.generateFallbackOrders(),
          showOfflineMessage: false, // 不显示离线消息，我们有自己的处理
          enableRetry: true
        }
      )
      
      // 处理API返回的数据结构
      let orderList = []
      if (orders && orders.code === 200) {
        // 真实API返回的数据
        orderList = orders.data.orders || orders.data || []
      } else if (Array.isArray(orders)) {
        // 降级数据（直接是数组）
        orderList = orders
      } else {
        // 其他情况，使用空数组
        orderList = []
      }
      
      // 使用数据验证工具补全订单数据
      const completeOrders = orderList.map(order => completeOrder(order))
      
      // 根据状态筛选
      let filteredOrders = completeOrders
      if (this.data.selectedStatus !== 'all') {
        filteredOrders = completeOrders.filter(order => order.status === this.data.selectedStatus)
      }
      
      console.log('订单列表处理完成:', {
        原始数据: orderList.length,
        补全后: completeOrders.length,
        筛选后: filteredOrders.length,
        当前状态: this.data.selectedStatus
      })
      
      this.setData({
        orders: this.data.currentPage === 0 ? filteredOrders : [...this.data.orders, ...filteredOrders],
        hasMore: false, // 当前实现没有分页
        loading: false
      })
      
    } catch (error) {
      console.error('加载订单失败:', error)
      this.setData({ loading: false })
      
      // 使用智能错误处理
      httpErrorHandler.showErrorToast(error, {
        showModal: false,
        duration: 2000
      })
    }
  },

  // 生成降级订单数据（合并各种来源）
  generateFallbackOrders() {
    // 合并模拟订单和本地存储的订单
    const mockOrders = this.generateMockOrders()
    const localOrders = wx.getStorageSync('mockOrders') || []
    
    // 合并并去重
    const allOrders = [...mockOrders, ...localOrders]
    const uniqueOrders = allOrders.filter((order, index, self) => 
      index === self.findIndex(o => o.id === order.id)
    )
    
    return uniqueOrders.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
  },

  // 生成模拟订单数据
  generateMockOrders() {
    const now = new Date()
    const orders = [
      {
        id: 1,
        orderNo: 'ORD20240101001',
        status: 'DELIVERING',
        type: 'DELIVERY',
        totalAmount: '46.00',
        createdAt: new Date(now.getTime() - 2 * 60 * 60 * 1000), // 2小时前
        estimatedDeliveryTime: new Date(now.getTime() + 15 * 60 * 1000), // 15分钟后
        deliveryAddress: '北京市朝阳区三里屯路19号院',
        store: {
          id: 1,
          name: '麦当劳(王府井店)',
          avatarUrl: '/images/stores/mcdonalds.jpg'
        },
        items: [
          {
            productId: 1,
            name: '巨无霸',
            image: '/images/products/bigmac.jpg',
            price: 24.5,
            quantity: 1,
            specifications: '{"size":"标准"}'
          },
          {
            productId: 3,
            name: '薯条(大)',
            image: '/images/products/fries.jpg',
            price: 12.0,
            quantity: 1,
            specifications: '{"size":"大份"}'
          }
        ]
      },
      {
        id: 2,
        orderNo: 'ORD20240101002',
        status: 'COMPLETED',
        type: 'DELIVERY',
        totalAmount: '57.50',
        createdAt: new Date(now.getTime() - 24 * 60 * 60 * 1000), // 1天前
        completedAt: new Date(now.getTime() - 23 * 60 * 60 * 1000),
        deliveryAddress: '北京市海淀区中关村大街1号',
        store: {
          id: 2,
          name: '肯德基(三里屯店)',
          avatarUrl: '/images/stores/kfc.jpg'
        },
        items: [
          {
            productId: 5,
            name: '新奥尔良烤翅',
            image: '/images/products/spicy-chicken.jpg',
            price: 16.0,
            quantity: 2,
            specifications: '{"count":"2只"}'
          },
          {
            productId: 7,
            name: '香辣鸡腿堡',
            image: '/images/products/burger.jpg',
            price: 22.0,
            quantity: 1,
            specifications: '{"spicy":"中辣"}'
          }
        ]
      },
      {
        id: 3,
        orderNo: 'ORD20240101003',
        status: 'PENDING_PAYMENT',
        type: 'DINE_IN',
        totalAmount: '128.00',
        createdAt: new Date(now.getTime() - 30 * 60 * 1000), // 30分钟前
        store: {
          id: 3,
          name: '海底捞火锅(中关村店)',
          avatarUrl: '/images/stores/haidilao.jpg'
        },
        items: [
          {
            productId: 8,
            name: '番茄锅底',
            image: '/images/products/hotpot.jpg',
            price: 38.0,
            quantity: 1,
            specifications: '{"spicy":"不辣"}'
          },
          {
            productId: 10,
            name: '精品肥牛',
            image: '/images/products/soup.jpg',
            price: 58.0,
            quantity: 1,
            specifications: '{"weight":"200g"}'
          }
        ]
      }
    ]
    
    return orders
  },

  // 刷新订单列表
  refreshOrders() {
    this.setData({
      currentPage: 0,
      orders: [],
      hasMore: true
    })
    this.loadOrders()
    wx.stopPullDownRefresh()
  },

  // 加载更多
  loadMore() {
    if (!this.data.hasMore || this.data.loading) return
    
    this.setData({
      currentPage: this.data.currentPage + 1
    })
    this.loadOrders()
  },

  // 选择状态
  selectStatus(e) {
    const status = e.currentTarget.dataset.status
    if (status === this.data.selectedStatus) return
    
    this.setData({ selectedStatus: status })
    this.refreshOrders()
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'PENDING_PAYMENT': '待支付',
      'PAID': '已支付',
      'PREPARING': '制作中',
      'READY': '待取餐',
      'DELIVERING': '配送中',
      'COMPLETED': '已完成',
      'CANCELLED': '已取消',
      'REFUNDED': '已退款'
    }
    return statusMap[status] || status
  },

  // 格式化时间
  formatTime(time) {
    if (!time) return ''
    
    const date = new Date(time)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    
    if (diff < 60 * 1000) {
      return '刚刚'
    } else if (diff < 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 1000))}分钟前`
    } else if (diff < 24 * 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
    } else {
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }
  },

  // 跳转到订单详情
  goToOrderDetail(e) {
    const order = e.currentTarget.dataset.order
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${order.id}`
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 取消订单
  cancelOrder(e) {
    const order = e.currentTarget.dataset.order
    this.setData({
      selectedOrder: order,
      showCancelModal: true,
      selectedReason: ''
    })
  },

  // 隐藏取消弹窗
  hideCancelModal() {
    this.setData({ showCancelModal: false })
  },

  // 选择取消原因
  selectCancelReason(e) {
    const reason = e.currentTarget.dataset.reason
    this.setData({ selectedReason: reason })
  },

  // 确认取消订单
  async confirmCancel() {
    if (!this.data.selectedReason) {
      wx.showToast({
        title: '请选择取消原因',
        icon: 'none'
      })
      return
    }
    
    const orderId = this.data.selectedOrder.id
    const reason = this.data.selectedReason
    
    try {
      wx.showLoading({ title: '取消中...' })
      
      console.log('开始取消订单:', { orderId, reason })
      
      // 调用真实API取消订单
      try {
        const result = await api.cancelOrder(orderId, reason)
        
        if (result.code === 200) {
          console.log('订单取消成功:', result)
          
          wx.hideLoading()
          wx.showToast({
            title: '订单已取消',
            icon: 'success'
          })
          
          // 更新本地订单状态
          const orders = this.data.orders.map(order => {
            if (order.id === orderId) {
              return { 
                ...order, 
                status: 'CANCELLED',
                cancelReason: reason,
                cancelTime: new Date()
              }
            }
            return order
          })
          
          this.setData({
            orders,
            showCancelModal: false,
            selectedOrder: null,
            selectedReason: ''
          })
          
        } else {
          throw new Error(result.message || '取消订单失败')
        }
        
      } catch (apiError) {
        console.log('API取消失败，使用模拟取消:', apiError.message)
        
        // API调用失败时使用模拟取消
        wx.hideLoading()
        wx.showToast({
          title: '订单已取消',
          icon: 'success'
        })
        
        // 更新订单状态
        const orders = this.data.orders.map(order => {
          if (order.id === orderId) {
            return { 
              ...order, 
              status: 'CANCELLED',
              cancelReason: reason,
              cancelTime: new Date()
            }
          }
          return order
        })
        
        this.setData({
          orders,
          showCancelModal: false,
          selectedOrder: null,
          selectedReason: ''
        })
      }
      
    } catch (error) {
      console.error('取消订单失败:', error)
      wx.hideLoading()
      
      wx.showModal({
        title: '取消失败',
        content: error.message || '取消订单失败，请重试',
        showCancel: false,
        confirmText: '知道了'
      })
    }
  },

  // 支付订单
  payOrder(e) {
    const order = e.currentTarget.dataset.order
    
    // 跳转到订单详情页面并触发支付
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${order.id}&needPay=true`
    })
  },

  // 查看物流
  trackOrder(e) {
    const order = e.currentTarget.dataset.order
    wx.showToast({
      title: '配送员正在路上',
      icon: 'none'
    })
  },

  // 确认收货
  confirmOrder(e) {
    const order = e.currentTarget.dataset.order
    
    wx.showModal({
      title: '确认收货',
      content: '确认已收到商品吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '确认收货成功',
            icon: 'success'
          })
          
          // 更新订单状态
          const orders = this.data.orders.map(item => {
            if (item.id === order.id) {
              return { ...item, status: 'COMPLETED' }
            }
            return item
          })
          
          this.setData({ orders })
        }
      }
    })
  },

  // 评价订单
  reviewOrder(e) {
    const order = e.currentTarget.dataset.order
    wx.navigateTo({
      url: `/pages/review/review?orderId=${order.id}&storeId=${order.store.id}`
    })
  },

  // 再来一单
  reorder(e) {
    const order = e.currentTarget.dataset.order
    
    // 将订单商品添加到购物车
    order.items.forEach(item => {
      const product = {
        id: item.productId,
        name: item.name,
        price: item.price,
        imageUrl: item.image,
        specifications: item.specifications
      }
      
      for (let i = 0; i < item.quantity; i++) {
        app.addToCart(product, order.store.id)
      }
    })
    
    wx.showToast({
      title: '已加入购物车',
      icon: 'success'
    })
    
    // 跳转到店铺详情
    setTimeout(() => {
      wx.navigateTo({
        url: `/pages/store-detail/store-detail?id=${order.store.id}&orderType=delivery`
      })
    }, 1500)
  },

  // 联系商家
  contactStore(e) {
    const order = e.currentTarget.dataset.order
    
    // 安全检查：确保order和store对象存在
    if (!order || !order.store) {
      wx.showToast({
        title: '订单信息异常',
        icon: 'none'
      })
      return
    }
    
    // 获取商家信息，提供默认值
    const storePhone = order.store.phone || '010-12345678'
    const storeName = order.store.name || '商家'
    
    wx.showModal({
      title: '联系商家',
      content: `${storeName}\n电话：${storePhone}`,
      showCancel: true,
      cancelText: '取消',
      confirmText: '拨打电话',
      success: (res) => {
        if (res.confirm) {
          // 尝试拨打电话
          wx.makePhoneCall({
            phoneNumber: storePhone,
            fail: (error) => {
              console.error('拨打电话失败:', error)
              wx.showToast({
                title: '拨打失败，请手动拨打',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },

  // 去逛逛
  goShopping() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }
}) 